import StorageTools from '../../tools/StorageTools'
import { Base64 } from 'js-base64'
export const clientInfo={
    clientId: 'pc_client',
    clientSecret: 'test_secret'
}
/**
 * 登录成功处理token事宜
 * @param res
 */
export function handleToken(res) {
    let access_token = res.data.access_token
    let access_token_payload_json = JSON.parse(Base64.decode(access_token.split('.')[1]))

    // 解析用户id 请求的时候带上，配合后台实现灰度路由
    StorageTools.sessionSet('userId',access_token_payload_json.user_name)

    let refresh_token = res.data.refresh_token
    let refresh_token_payload_json = JSON.parse(Base64.decode(refresh_token.split('.')[1]))


    StorageTools.sessionSet('Authorization','Bearer ' + access_token)
    StorageTools.sessionSet('access_token', access_token)
    StorageTools.sessionSet('refresh_token', refresh_token)

    let access_token_expires_at = res.data.expires_in * 1000 + new Date().getTime()
    StorageTools.sessionSet('access_token_expires_at', access_token_expires_at)
    StorageTools.sessionSet('refresh_token_expires_at', access_token_expires_at + (refresh_token_payload_json.exp - access_token_payload_json.exp) * 1000)
}

/**
 * 清除登录时的token
 */
export function clearToken() {
    StorageTools.sessionClearKeys(['Authorization','access_token','refresh_token','access_token_expires_at','refresh_token_expires_at','userId'])
}
export function isAccessTokenNearExpires(inMin = 3) {
    let access_token_expires_at = StorageTools.sessionGet('access_token_expires_at')
    if (access_token_expires_at) {
        let now = new Date().getTime()
        if(access_token_expires_at - now > 0 &&  access_token_expires_at - now < inMin * 60 *1000){
            return true
        }
        return false
    }
    return undefined
}
export function isAccessTokenExpires() {
    let access_token_expires_at = StorageTools.sessionGet('access_token_expires_at')
    if (access_token_expires_at) {
        let now = new Date().getTime()
        if(now >= access_token_expires_at){
            return true
        }
        return false
    }
    return undefined
}
export function isRefreshTokenExpires() {
    let refresh_token_expires_at = StorageTools.sessionGet('refresh_token_expires_at')
    if (refresh_token_expires_at) {
        let now = new Date().getTime()
        if(now >= refresh_token_expires_at){
            return true
        }
        return false
    }
    return undefined
}

export function refreshToken (axios,vue) {
    // instance是当前request.js中已创建的axios实例
    return axios.post(vue.prototype.$baseURL.auth +  '/oauth/token?scope=read&grant_type=refresh_token',
        'refresh_token=' + StorageTools.sessionGet('refresh_token'),
        {
            headers:{
                'Content-Type': 'application/x-www-form-urlencoded',
                Authorization: 'Basic ' + Base64.encode(clientInfo.clientId + ':' + clientInfo.clientSecret)
            }
        }).then(res => {
        handleToken(res)
        return Promise.resolve(res)
    }).catch(()=>{
        clearToken()
    })
}
export function handleAxiosRequestConfig(config) {

    if (!config.headers.Authorization && StorageTools.sessionGet('Authorization')) { // 判断是否存在token，如果存在的话，则每个http header都加上token
        config.headers.Authorization = StorageTools.sessionGet('Authorization')  //请求头加上token
    }
    // 添加一个用户id请求头，主要是本地开发环境内存不足，和服务器共用其它模块，根据这个请求头实现灰度路由，以达到访问本地的目的
    // 如果不需要删除即可
    if (!config.headers.userId && StorageTools.sessionGet('userId')) {
        config.headers.userId = StorageTools.sessionGet('userId')
    }
}